package com.li.my_tiny_spring.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.li.my_tiny_spring.exception.impl.MyIllegalStateException;

import jdk.nashorn.internal.ir.ObjectNode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtil {
	public static ArrayNode createArray(){
		ObjectMapper mapper = new ObjectMapper();
		return mapper.createArrayNode();
	}
	private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
		ObjectMapper mapper = new ObjectMapper();
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);   
    }
	public static <E> List<E> toList(String text,Class<E> clazz){
		 try {
			 ObjectMapper mapper = new ObjectMapper();
			 JavaType javaType = getCollectionType(ArrayList.class, clazz); 
			return mapper.readValue(text, javaType);
		} catch (IOException e) {
			throw new MyIllegalStateException(e);
		}
	} 
	public static <E> E toObject(String text,Class<E> clazz){
		try {
			ObjectMapper mapper = new ObjectMapper();
			return  (E) mapper.readValue(text, clazz);
		} catch (IOException e) {
			throw new MyIllegalStateException(e);
		}
	} 
	@Getter
	@Setter
	@ToString
	private static class Temp{
		private int id=1;
	}
	public static String toFormatString(Object obj) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new MyIllegalStateException(e);
		}
	}
	public static String toString(Object object) {
		ObjectMapper m = new ObjectMapper();
		try {
			return m.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			log.error("write error ,object is:"+object, e);
			return "";
		}
	}
}
